package com.yikun.springbootinit.datasource;

import com.yikun.springbootinit.model.enums.SearchTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <h1>使用注册器模式来管理多个数据源对象<h1>
 *
 * @ClassName: DataSourceRegistry
 * @Author: 初久
 * @Date: 2023/4/6 22:19
 **/
@Component
@Slf4j
public class DataSourceRegistry {

    @Resource
    private PostDataSource postDataSource;

    @Resource
    private UserDataSource userDataSource;

    @Resource
    private PictureDataSource pictureDataSource;

    private Map<String, DataSource<?>> typeDataSourceMap;

    /**
     * 初始化枚举类型字符串与其对应实例 bean 的 map
     */
    @PostConstruct
    public void initMap() {
        typeDataSourceMap = new HashMap<String, DataSource<?>>() {{
            put(SearchTypeEnum.POST.getValue(), postDataSource);
            put(SearchTypeEnum.USER.getValue(), userDataSource);
            put(SearchTypeEnum.PICTURE.getValue(), pictureDataSource);
        }};
    }

    public DataSource getDataSourceByType(String type) {
        if (null == typeDataSourceMap) {
            log.error("typeDataSourceMap 为空！");
            return null;
        }

        return typeDataSourceMap.get(type);
    }

}
